// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.asm;

import java.util.Set;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * Visitor which collects indices of local variables which are being written by
 * method's code.
 * 
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class WriteLocalsCollector extends BaseMethodVisitor {

  private final Set<Integer> writtenLocals;

  public WriteLocalsCollector(Set<Integer> writtenLocals) {
    this.writtenLocals = writtenLocals;
  }

  @Override
  public void visitIincInsn(int var, int increment) {
    writtenLocals.add(var);
  }

  @Override
  public void visitVarInsn(int opcode, int var) {
    switch (opcode) {
      case Opcodes.ASTORE:
      case Opcodes.ISTORE:
      case Opcodes.LSTORE:
      case Opcodes.FSTORE:
      case Opcodes.DSTORE:
        writtenLocals.add(var);
        break;
      case Opcodes.RET:
        // TODO(micapolos): What is RET?
        throw new RuntimeException("RET not supported");
    }
  }
}
